package com.yizhuoyan.his.algorithm;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class SnowFlake64Id {
    //时间戳占2进制位数，默认41位
    private static final int TIMESTAMP_BITS = 41;

    //时间戳开始时间点，保证当前时间戳减去开始时间点的结果不超过41位2进制的最大值
    //private final static long TIMESTAMP_START_EPOCH = 1288834974657L;
    //统一从2020年1月1日开始
    private final static long TIMESTAMP_START_EPOCH = Instant.parse("2020-01-01T00:00:00Z").toEpochMilli();
    //机器id所占2进制位数，默认5位
    private static final int WORKER_GROUP_ID_BITS = 5;
    //机器id所占2进制位数，默认5位
    private static final int WORKER_ID_BITS = 5;
    //生成序号占2进制位数，默认12位
    private static final int SEQUENCE_BITS = 12;
    //时间戳开始位置=12+5+5
    private static final int TIMESTAMP_OFFSET = SEQUENCE_BITS + WORKER_ID_BITS + WORKER_GROUP_ID_BITS;
    //机器组id开始位置=12+5
    private static final int WORKER_GROUP_ID_OFFSET = SEQUENCE_BITS + WORKER_ID_BITS;
    //机器id开始位置=12
    private static final int WORKER_ID_SHIFT = SEQUENCE_BITS;

    // 机器最大id=32
    private static final int MAX_WORKER_ID = ~(-1<< WORKER_ID_BITS);
    //机器所属组最大id=32
    private static final int MAX_WORKER_GROUP_ID = ~(-1<< WORKER_GROUP_ID_BITS);
    //最大序号=4096(表示1ms最大并发量)
    private static final int MAX_SEQUENCE = ~(-1 << SEQUENCE_BITS);

    /**
     * 当前机器id
     */
    private final int workerId;
    /**
     * 当前机器所属组id
     */
    private final int workerGroupId; // 这个就是代表了
    // 当前序号
    private int sequence;
    /**
     * 上一次生成后的时间戳
     */
    private long lastTimestamp =0;


    /**
     * @param workerId 机器id
     * @param workerGroupId 机房id
     * @param sequence
     * @throws  IllegalArgumentException 如果workerId大于
     */
    public SnowFlake64Id(int workerId, int workerGroupId, int sequence) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException(
                    String.format("worker Id can't be greater than %d or less than 0", MAX_WORKER_ID));
        }
        if (workerGroupId > MAX_WORKER_GROUP_ID || workerGroupId < 0) {
            throw new IllegalArgumentException(
                    String.format("workerGroup Id can't be greater than %d or less than 0", MAX_WORKER_GROUP_ID));
        }
        this.workerId = workerId;
        this.workerGroupId = workerGroupId;
        this.sequence = sequence;
    }
    public SnowFlake64Id(int workerId) {
        this(workerId,1,0);
    }
    public SnowFlake64Id(int workerId, int workerGroupId) {
        this(workerId,workerGroupId,0);
    }
    /**
     * 生成下一个可用id
     * @return 可用id
     */
    public synchronized long nextId() {
        // 当前时间戳
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            //Clock moved backwards. Refusing to generate
            throw new RuntimeException("should never happen");
        }
        //同一个毫秒内，增加序列号
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //毫秒数用完，使用下一个时间戳
            if (sequence == 0) {
                timestamp = utilNextMillis(lastTimestamp);
            }
        } else {
            //不同毫秒，序号从0又开始
            sequence = 0;
        }
        //保存本次使用时间戳
        lastTimestamp = timestamp;

        return ((timestamp - TIMESTAMP_START_EPOCH) << TIMESTAMP_OFFSET) |
                (workerGroupId << WORKER_GROUP_ID_OFFSET) |
                (workerId << WORKER_ID_SHIFT) | sequence;
    }

    /**
     * 自旋，保证毫秒数大于传入毫秒数
     * @param lastTimestamp 传入毫秒数
     * @return 最近毫秒数
     */
    private long utilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }


    //---------------测试---------------
    public static void main(String[] args) {
        SnowFlake64Id worker = new SnowFlake64Id(1);
        for (int i = 0; i < 30; i++) {
           System.out.println(worker.nextId());
        }
    }
}
